<?php
namespace app\api\controller;
use think\Controller;
use think\Validate;
use think\Config;

class Spike extends Controller{
    //限时秒杀
    //秒杀商品列表
    public function seckillGoodsList(){
       $page = input('post.page');
       if($page){if(!is_numeric($page)){return json_encode(['code'=>401,'msg'=>'page参数类型错误']);}}else{$page = 0;}
       $user_id = input('post.user_id');
       if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'usr_id类型错误']);}
       //price 秒杀价格 start_time 开始时间 end_time 结束时间 limits限制次数
       $goods_list = db('goods_seckill')->field('seckill_id,goods_id,spec_item,price,start_time,end_time,limits')
                                        ->where("state = 1")
                                        ->order("seckill_id desc")
                                        ->limit($page*5,5)
                                        ->select();
       foreach($goods_list as $key=>$value){
          if(time() < $value['start_time']){
             $goods_list[$key]['activity_status'] = 0;//0表示活动未开始;
           }elseif(time() > $value['end_time']){
             $goods_list[$key]['activity_status'] = 2;//2表示活动已结束
           }else{
             $goods_list[$key]['activity_status'] = 1;//1表示活动已开始;
          }
          unset($goods_list[$key]['start_time']);
          $goods_list[$key]['end_time'] = date("Y-m-d H:i:s",$value['end_time']);
          $goods_info = db('goods')->field('name as goods_name,mode,thumbnail_img')->where("goods_id = {$value['goods_id']}")->find();
          $goods_list[$key]['goods_name'] = $goods_info['goods_name'];
          $goods_list[$key]['mode'] = $goods_info['mode'];//0一口价;1多规格;
          if(!Validate::is($goods_info['thumbnail_img'],'url')){
              $goods_list[$key]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$goods_info['thumbnail_img'];
          }
          $map = "goods_id = {$value['goods_id']} AND price_key = {$value['spec_item']}";
          $spec_info = db('spec_goods_price')->field('store,price')->where($map)->find();
          $goods_list[$key]['store'] = $spec_info['store'];//商品库存;
          $goods_list[$key]['goods_price'] = $spec_info['price'];//商品价格;
          if($value['spec_item'] != 0){
             $goods_list[$key]['spec_name'] = db('spec_item')->where("item_id = {$value['spec_item']}")->value('spec_item');//规格名称;
          }
          $seckill_num = db('goods_success_killed')->where("seckill_id = {$value['seckill_id']} AND user_id = {$user_id}")->count(); //秒杀成功的次数;
          if($seckill_num > $value['limits']){
             $goods_list[$key]['is_buy'] = 1;
          }else{
             $goods_list[$key]['is_buy'] = 0;//0表示能继续进行秒杀活动;1表示秒杀活动次数已用完;
          }
          $goods_list[$key]['goods_type'] = 1;//1秒杀;2砍价;
       }
       if($goods_list){
           return json_encode(['code'=>200,'msg'=>'请求成功','goods_list'=>$goods_list]);
       }else{
           return json_encode(['code'=>201,'msg'=>'暂无数据']);
       }
    }
}